# -*- coding: utf-8 -*-
import os
import time

import requests

from util.selenium import webdriver

from PIL import Image
from io import BytesIO

from settings import validate_code_path, chrome_driver_path


class GetImg():

    def __init__(self, driver=None, cookies_dict={}):
        self.driver = driver
        self.cookies_dict = cookies_dict
        # self.driver = webdriver.Chrome()
        self.headers = {
            # 'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3554.0 Safari/537.36",
            # 'Accept-Encoding': 'gzip, deflate, br',
            # 'Accept-Language': 'zh-CN,zh;q=0.9',
            # 'Connection': 'keep-alive',
            # 'Referer': 'https://tyrz.chinatorch.org.cn/hjismp/a/login',
            # "Upgrade-Insecure-Requests": "1",
            # "Cache-Control": "max-age=0",
            # "Host": "fuwu.most.gov.cn",
            # "Regerer": "https://fuwu.most.gov.cn/authentication/sso/login",
            # "Cookie": "JSESSIONID=9A910A29EB6BA86EA85879C4D8C0DEAF; JSESSIONID=8D689844A6D726293696DC43FABC5942; portal_authentication.session.id=12bb2d397e634e4db3b3ff8a1d5f00a4; _site_id_cookie=1; clientlanguage=zh_CN; JSESSIONID=945391C37139F69A0956047097133175; jeesite.session.id=bf0d1ff3e5cb4d61a3c4f3808502649e"
        }

    def get_img(self, ele_loc=()):

        # url = self.driver.find_element_by_css_selector('.iconBox .yanzhengma img').get_attribute('src')
        if not self.driver:
            url = 'https://fuwu.most.gov.cn/authentication/servlet/validateCodeServlet?width=88&height=38&v='
        else:
            url = self.driver.find_element(*ele_loc).get_attribute('src')
        self.set_cookie()
        img_path = self.download_img_and_return_imgpath(url)
        # img_path = self.cut_img_and_return_imgpath()
        # print(img_path)
        return img_path

    def set_cookie(self):
        if not self.driver:
            cookiestr = "; ".join("{}={}".format(k, v) for k, v in self.cookies_dict.items())
        else:
            cookie = [item["name"] + "=" + item["value"] for item in self.driver.get_cookies()]
            # cookie = [item["name"] + "=" + item["value"] for item in cookies]
            cookiestr = '; '.join(item for item in cookie)
        # print(cookiestr)
        self.headers['Cookie'] = cookiestr

    def download_img_and_return_imgpath(self, url):
        # sysCode=gq; jeesite.session.id=4eeddb0a83964a8ba576bee7ab6bdd7c; insert_cookie=72971929
        res = None
        while True:
            try:
                res = requests.get(url, headers=self.headers)
                # res = requests.get(url)
            except Exception as err:
                pass
            else:
                if res.status_code == 200:
                    break
        if not os.path.exists(validate_code_path):
            os.makedirs(validate_code_path)
        img_path = '{}{}_validate_code_img.jpg'.format(validate_code_path, time.strftime('%Y-%m-%d %H-%M-%S')).replace(
            '\\', '/')

        with open(img_path, 'wb') as f:
            f.write(res.content)

        return img_path

    def cut_img_and_return_imgpath(self):
        img_path = '{}{}_validate_code_img.png'.format(validate_code_path, time.strftime('%Y-%m-%d %H-%M-%S'))

        screen_shot = self.driver.get_screenshot_as_png()  # 获取全屏截图的对象
        screen_image = Image.open(BytesIO(screen_shot))  # 以IO的形式转换为二进制
        screen_image.save('../images/00_screen_image.png')

        # 对验证码图片区域进行截图，保存
        code_image_el = self.driver.find_element_by_css_selector('img.mid.validateCode')  # 获取验证码图片对象

        height = code_image_el.size['height'] + 10
        width = code_image_el.size['width'] + 13

        left = code_image_el.location['x'] + 245
        top = code_image_el.location['y'] + 97
        right = left + width
        bottom = top + height

        # 验证码图片--区域位置信息
        cut_info = (left, top, right, bottom)
        print(cut_info)

        # 截图操作,保存截图
        cut_image = screen_image.crop(cut_info)
        cut_image.save(img_path)

        return img_path


if __name__ == '__main__':
    # 可用requests请求获取验证码图片

    # driver = webdriver.Chrome(executable_path=chrome_driver_path)
    # driver.get('https://tyrz.chinatorch.org.cn/hjismp/a?login')
    # driver.maximize_window()
    # driver.implicitly_wait(15)
    #
    #
    a = GetImg("")

    img_path = a.get_img()

    pass
